package com.lc.ei.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.lc.ei.service.DataService;
import com.study.common.entity.dto.ExportDto;
import com.study.common.utils.NoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @description: some desc
 * @author: LChuang
 * @date: 2023/9/1 11:15
 */
@Slf4j
@RestController
@RequestMapping("/file/excel")
public class ExcelController {

    @Resource
    private DataService dataService;

    @PostMapping("/export")
    public void export(HttpServletResponse response){
        String fileName = NoUtil.create().concat(ExcelTypeEnum.XLSX.getValue());
        this.setResponse(response, fileName);
        List<ExportDto> list = dataService.getExportData();
        try {
            EasyExcel.write(response.getOutputStream(), ExportDto.class).sheet("导出数据").doWrite(list);
        } catch (IOException e) {
            log.error("文件导出异常：{}", e.getMessage());
        }
    }

    @PostMapping("/import")
    public List<ExportDto> importFile(@RequestPart(value = "file") MultipartFile file){
        try {
            return EasyExcel.read(file.getInputStream()).head(ExportDto.class).sheet().doReadSync();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }



    private void setResponse(HttpServletResponse response, String fileName){
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName );
    }

}
